/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package university.location;

import java.awt.event.ActionEvent;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import org.postgis.Point;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "university_location")
@ViewScoped
public class Main extends Beans implements Serializable {
    //Variables de importación General

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    //Variables de importación otros modulos
    //Variables del modulo
    private Find university_basedFind = new Find();
    private Double lat = 8.932509021104444;
    private Double lng = -79.8275537603455;
    private MapModel emptyModel;
    private List<Beans> sedeList = new ArrayList<>();
    private Marker marker;
    //Variables locales
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
        emptyModel = new DefaultMapModel();
    }

    public void load() {
        try {

            /*
             * sql = "SELECT ub.id, ub.univerisidad,ub.id_corregimiento,
             * ub.direccion, ub.nombre " + "FROM public.v_universidad_sede ub" +
             * "INNER JOIN public.v_universidad u" + "ON
             * (ub.id_universidad=u.id) " + "WHERE ub.id = " +
             */
            map.clear();
            map.put("us.id = " + logged.getDetailId(), " ");

            sedeList.clear();
            sedeList = university_basedFind.byMap(map);

            setId(sedeList.get(0).getId());
            logged.setMasterId(sedeList.get(0).getId_universidad());
            setId_Corregimiento(sedeList.get(0).getId_Corregimiento());
            setDireccion(sedeList.get(0).getDireccion());
            setNombre(sedeList.get(0).getNombre());
            getCountryBeans().setId(sedeList.get(0).getCountryBeans().getId());
            getProvinceBeans().setId(sedeList.get(0).getProvinceBeans().getId());
            getDistrictBeans().setId(sedeList.get(0).getDistrictBeans().getId());
            setGeometry(sedeList.get(0).getGeometry());
            Point p = new Point(getGeometry().getValue());
            setLng(p.getX());
            setLat(p.getY());


        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() throws Exc, SQLException, Exception {
        try {
            //Verifica si se ha seleccionado un regi

            if (logged.getMasterId() == 0) {
                throw new Exc("m21");
            }

            //carga el mapa con lo valores de la llave unica
            map.clear();
            map.put("id_universidad = " + logged.getMasterId(), " AND ");
            map.put("id_corregimiento = " + getId_Corregimiento(), " AND ");
            map.put("lower(direccion) = '" + getDireccion().toLowerCase() + "'", " AND ");
            map.put("lower(us.nombre) = '" + getNombre().toLowerCase() + "'", " ");

            if (university_basedFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "INSERT INTO public.universidad_sede (id_universidad,id_corregimiento, direccion, nombre, geometry) "
                    + "VALUES (" + logged.getMasterId() + "," + getId_Corregimiento() + ",'" + getDireccion() + "','" + getNombre() + "', ST_GeomFromText('POINT(" + getLng() + " " + getLat() + ")',4326))";

            persistencia.executeUpdate(sql);

            throw new Exc("m1");
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }

    }

    public void update() {
        try {

            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m6");
            }

            //Verifica si el registro existe, de lo contrario lo inserta
            map.clear();
            map.put("us.id <> " + logged.getDetailId(), " AND ");
            map.put("id_universidad = " + logged.getMasterId(), " AND ");
            map.put("id_corregimiento = " + getId_Corregimiento(), " AND ");
            map.put("lower(direccion) = '" + getDireccion().toLowerCase() + "'", " AND ");
            map.put("lower(us.nombre) = '" + getNombre().toLowerCase() + "'", " ");

            if (university_basedFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "UPDATE public.universidad_sede SET "
                    + "id_universidad = " + logged.getMasterId() + ", "
                    + "id_corregimiento = " + getId_Corregimiento() + ", "
                    + "direccion='" + getDireccion() + "', "
                    + "nombre='" + getNombre() + "', "
                    + "geometry = ST_GeomFromText('POINT(" + getLng() + " " + getLat() + ")',4326)"
                    + " WHERE id =" + logged.getDetailId();

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);

            throw new Exc("m2");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id_persona
            deleteById(logged.getDetailId());

            logged.setDetailId(0);
            clear();
            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        //Verifica si el usuario ya existe para otra persona
        sql = "DELETE FROM public.universidad_sede"
                + " WHERE id = " + id;
        persistencia.executeUpdate(sql);
    }

    public void clear() {
        clearBeans();
        logged.setDetailId(0);
        setLat(8.932509021104444);
        setLng(-79.8275537603455);
    }

    public void insertCountry() throws Exc, SQLException, Exception {
        location.general.Main paisMain = new location.general.Main();
        getCountryBeans().setId(paisMain.insert(getCountryBeans().getNombre()));
        getCountryBeans().setNombre("");
    }

    public void insertProvince() throws Exc, SQLException, Exception {
        location.province.Main provinceMain = new location.province.Main();
        getProvinceBeans().setId(provinceMain.insert(getCountryBeans().getId(), getProvinceBeans().getNombre()));
        getProvinceBeans().setNombre("");
    }

    public void insertDistrict() throws Exc, SQLException, Exception {
        location.district.Main districtMain = new location.district.Main();
        getDistrictBeans().setId(districtMain.insert(getProvinceBeans().getId(), getDistrictBeans().getNombre()));
        getDistrictBeans().setNombre("");
        // logged.setRecordId( getProvinceBeans().getId());
        // getDistrictBeans().setNombre("");
    }

    public void insertTownship() throws Exc, SQLException, Exception {
        location.township.Main townshipMain = new location.township.Main();
        setId_Corregimiento(townshipMain.insert(getDistrictBeans().getId(), getTownshipBeans().getNombre().toString()));
        getTownshipBeans().setNombre("");
    }

    public void selectedCountry(ValueChangeEvent event) {

        getCountryBeans().setId(Integer.parseInt(event.getNewValue().toString()));
    }

    public void selectedProvince(ValueChangeEvent event) {
        getProvinceBeans().setId(Integer.parseInt(event.getNewValue().toString()));
    }

    public void selectedDistrict(ValueChangeEvent event) {
        getDistrictBeans().setId(Integer.parseInt(event.getNewValue().toString()));
    }

    public void selectedTownship(ValueChangeEvent event) {
        setId_Corregimiento(Integer.parseInt(event.getNewValue().toString()));
    }

    public MapModel getEmptyModel() {
        return emptyModel;
    }

    public void addMarker(ActionEvent actionEvent) {
        emptyModel.getMarkers().clear();
        Marker marker = new Marker(new LatLng(lat, lng));
        emptyModel.addOverlay(marker);
    }

    public Marker getMarker() {
        return marker;
    }

    public void selectedTempId(int tempId) {
        logged.setDetailId(tempId);
        load();
    }

    public void selectedRecordId(int tempId) {
        logged.setDetailId(tempId);
        load();
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    public double getLng() {
        return lng;
    }

    public void setLng(double lng) {
        this.lng = lng;
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
